const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1]; // 从 Authorization 头部获取 token

  if (!token) {
    return res.status(403).json({
      code: 1003, // 无权限
      message: '未提供认证 Token'
    });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = {
      userId: decoded.id,
      username: decoded.username,
      roleId: decoded.roleId
    };
    next(); //通过

  } catch (error) {
    return res.status(401).json({
      code: 1003, // 无权限
      message: 'Token 无效或已过期'
    });
  }
};

module.exports = {
  authMiddleware: verifyToken
};
